package com.stxx.stiot2.controller;

import com.stxx.framwork.constants.SceneActionType;
import com.stxx.framwork.domain.R;
import com.stxx.framwork.domain.model.PageQuery;
import com.stxx.framwork.domain.model.PageResult;
import com.stxx.stiot2.domain.Gateway;
import com.stxx.stiot2.domain.Terminal;
import com.stxx.stiot2.event.dto.P2tMsg;
import com.stxx.stiot2.gateway.GatewayUtils;
import com.stxx.stiot2.gateway.face.GatewayServer;
import com.stxx.stiot2.service.TerminalService;
import org.noear.solon.annotation.*;

import java.sql.SQLException;

@Controller
@Mapping("/terminal")
public class TerminalController {

    @Inject
    TerminalService baseService;
    @Inject
    GatewayUtils gatewayUtils;

    @Get
    @Mapping("/list")
    public PageResult<Terminal> list(Terminal bo, PageQuery pageQuery) throws SQLException {
        PageResult<Terminal> r = baseService.pageList(bo,pageQuery);
        return r;
    }

    @Get
    @Mapping("/list-by-sw")
    public PageResult<Terminal> query(String sw, PageQuery pageQuery) throws SQLException {
        PageResult<Terminal> r = baseService.listBySw(sw,pageQuery);
        return r;
    }



    @Post
    @Mapping("")
    public R<Object> add(@Body Terminal bo) throws SQLException {
        baseService.insert(bo);
        return R.ok("数据保存成功");
    }

    @Put
    @Mapping("")
    public R<Object> edit(@Body Terminal bo) throws SQLException {
        baseService.update(bo);
        return R.ok("数据保存成功");
    }

    @Delete
    @Mapping("/{ids}")
    public R<Object> remove(@Path String[] ids) throws SQLException {
        baseService.deleteByIds(ids);
        return R.ok("数据删除成功");
    }

    @Get
    @Mapping("/{code}/call")
    public R<Object> call(@Path String code, String actionType,String msg) throws SQLException {
        Terminal terminal = baseService.queryById(code);
        GatewayServer server = gatewayUtils.getGateway(terminal.getCode());
        P2tMsg ptMsg = new P2tMsg();
        ptMsg.setType(actionType);
        ptMsg.setProperties(msg);
        server.send(terminal.getGatewayCode(),terminal.getCode(),ptMsg);
        return R.ok("数据保存成功");
    }

    @Get
    @Mapping("/{code}/create-device")
    public R<Object> createDevice(@Path String code) throws SQLException {
        Terminal terminal = baseService.queryById(code);
        baseService.createDevice(terminal);
        return R.ok("设备创建成功");
    }
}
